const router = require('koa-router')()

const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/api/blog')

router.get('/list', async function (ctx, next) {
    let author = ctx.query.author || ''
    const keyword = ctx.query.keyword || ''

    // 修改登录权限
    if (ctx.query.isadmin) {
        // 管理员界面
        if (ctx.session.username == null) {
            // 未登录情况
            ctx.body = new ErrorModel('未登录')
            return
        }
        // 强制查询自己的博客
        author = ctx.session.username
    }

    const listData = await getList(author, keyword)
    ctx.body = new SuccessModel(listData)
})

router.get('/detail', async function (ctx, next) {
    const listData = await getDetail(ctx.query.id)
    ctx.body = new SuccessModel(listData)
})

router.post('/new', loginCheck, async function (ctx, next) {
    const { body } = ctx.request
    body.author = ctx.session.username
    const data = await newBlog(body)
    ctx.body = new SuccessModel(data)
})

router.post('/update', loginCheck, async function (ctx, next) {
    const data = await updateBlog(ctx.query.id, ctx.request.body)

    if (data) {
        ctx.body = new SuccessModel()
        return 
    }

    ctx.body = new ErrorModel('update failed')
})

router.post('/delete', loginCheck, async function (ctx, next) {
    const author = ctx.session.username
    const data = await deleteBlog(ctx.query.id, author)

    if (data) {
        ctx.body = new SuccessModel()
        return
    }

    ctx.body = new ErrorModel('delete failed')
})

module.exports = router
